/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package socof.wget;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.JFrame;
import ui.UserInterface;

/**
 *
 * @author Carlos
 */
public class SOCOFWget
{

    protected static String localPath;
    protected static String site;
    protected static int maxBandwith;
    protected static float maxCpu;
    protected static int downloadersLimit = -1;
    protected static int parsersLimit = -1;
    protected static int maxLevel;
    
    protected static MainLaucher lb;

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException, InterruptedException
    {
        /*if (!getCommanLineArgs(args))
        {
            System.out.println("Invalid arguments. Valid options are:");
            System.out.println("");
            System.out.println("Mandatory arguments:");
            System.out.println("-localPath=<path to an existing local dir.>");
            System.out.println("-site=<url of site to be downloaded>");
            System.out.println("-maxBandwith=<max. bandwith allowed>");
            System.out.println("-maxCpu=<max. cpu usage (between 0 to 1)>");
            System.out.println("");
            System.out.println("Optional arguments:");
            System.out.println("-downloadersLimit=<max. number of parallel downloades>");
            System.out.println("-parsersLimit=<max. number of parallel parsers>");
            System.out.println("-maxLevel=<max. site level depth>");

            return;
        }*/
        
        JFrame frame = new JFrame("Wget SOCOF");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //Grafica grf=new UserInterface();
        
        frame.add(new UserInterface());
        frame.pack();
        frame.setVisible(true);
    }
    
    public static boolean setValues (String site, String localPath, String maxBandwith,
                                     String maxCpu, String downloadersLimit, String parsersLimit,
                                     String maxLevel)
    {
        if (!site.startsWith("http://") && !site.startsWith("https://"))
            SOCOFWget.site = "http://" + site;
        else
            SOCOFWget.site = site;
        
        SOCOFWget.localPath = localPath;
        
        try
        {
            SOCOFWget.maxBandwith = Integer.parseInt(maxBandwith);
        }
        catch (NumberFormatException ex)
        {
            SOCOFWget.maxBandwith = 0;
        }
                
        try
        {
            SOCOFWget.maxCpu = Float.parseFloat(maxCpu);
        }
        catch (NumberFormatException ex)
        {
            SOCOFWget.maxCpu = 0.0f;
        }

        try
        {
            SOCOFWget.downloadersLimit = Integer.parseInt(downloadersLimit);
        }
        catch (NumberFormatException ex)
        {
            SOCOFWget.downloadersLimit = 0;
        }

        try
        {
            SOCOFWget.parsersLimit = Integer.parseInt(parsersLimit);
        }
        catch (NumberFormatException ex)
        {
            SOCOFWget.parsersLimit = 0;
        }

        try
        {
            SOCOFWget.maxLevel = Integer.parseInt(maxLevel);
        }
        catch (NumberFormatException ex)
        {
            SOCOFWget.maxLevel = 0;
        }
        
        return checkArgsAreValid();        
    }
    
    public static void startProcess()
    {
        try
        {
            lb = MainLaucher.getInstance();
            
            // base url to db
            WebResource.setBasePath(localPath);
            WebResource wr = new WebResource(site);        
            if (maxLevel > 0)
            {
                String[] s = site.split("/");
                WebResource.setMaxLevel(s.length + maxLevel); 
            }

            ToDownloadQueue.getInstance().offer(wr);

            lb.setMaxBandwithAllocation(maxBandwith);
            lb.setMaxCpuUsage(maxCpu);

            if (downloadersLimit > 0)
                lb.setDownloadersLimit(downloadersLimit);

            if(parsersLimit > 0)
                lb.setParsersLimit(parsersLimit);

            ParsedSet.getInstance().clear();
            
            lb.start();
        }
        catch (IOException ex)
        {
        }
    }
    
    public static void pause ()
    {
        lb.pauseProcess();
    }
    
    public static void resume ()
    {
        lb.resumeProcess();
    }
    
    public static void finish()
    {
        try
        {
            lb.interrupt();
            lb.join();
        }
        catch (InterruptedException ex)
        {
            //Logger.getLogger(SOCOFWget.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static int getNumberExecutingDownloaders()
    {
        return DownloadersBalancer.getInstance().getNumberExecuting();
    }
    
    public static int getNumberExecutingParsers()
    {
        return ParsersBalancers.getInstance().getNumberExecuting();
    }
    
    public static String[] getUrlsDownloaded()
    {
        return DownloadedSet.getInstance().getStringArray();
    }
    
    public static String[] getFilesParsed()
    {
        return ParsedSet.getInstance().getStringArray();
    }
            
    protected static boolean getCommanLineArgs(String[] args)
    {
        for (String s : args)
        {
            if (s.startsWith("-localPath="))
            {
                localPath = getValFromArg(s);
            }
            if (s.startsWith("-site="))
            {
                site = getValFromArg(s);
            }
            if (s.startsWith("-maxBandwith="))
            {
                try
                {
                    maxBandwith = Integer.parseInt(getValFromArg(s));
                }
                catch (NumberFormatException ex)
                {
                    maxBandwith = 0;
                } 
            }
            if (s.startsWith("-maxCpu="))
            {
                try
                {
                    maxCpu = Float.parseFloat(getValFromArg(s));
                }
                catch (NumberFormatException ex)
                {
                    maxCpu = 0.0f;
                }                
            }
            if (s.startsWith("-downloadersLimit="))
            {
                try
                {
                    downloadersLimit = Integer.parseInt(getValFromArg(s));
                }
                catch (NumberFormatException ex)
                {
                    downloadersLimit = 0;
                }
            }
            if (s.startsWith("-parsersLimit="))
            {
                try
                {
                    parsersLimit = Integer.parseInt(getValFromArg(s));
                }
                catch (NumberFormatException ex)
                {
                    parsersLimit = 0;
                }
            }
            if (s.startsWith("-maxLevel="))
            {
                try
                {
                    maxLevel = Integer.parseInt(getValFromArg(s));
                }
                catch (NumberFormatException ex)
                {
                    maxLevel = 0;
                }
            }
        }

        return checkArgsAreValid();
    }

    private static String getValFromArg(String arg)
    {
        String[] s = arg.split("=");
        if (s.length == 2)
        {
            return s[1];
        }
        else
        {
            return null;
        }

    }

    private static boolean checkArgsAreValid()
    {
        boolean valid = true;
        try
        {
            File dir = new File(localPath);
            if (!dir.isDirectory())
            {
                valid = false;
            }
        }
        catch (Exception ex)
        {
            valid = false;
        }

        try
        {               
            URL url = new URL(site);
        }
        catch (MalformedURLException ex)
        {
            valid = false;
        }

        if (maxBandwith <= 0 || maxCpu <= 0)
        {
            valid = false;
        }

        if (parsersLimit == 0 && downloadersLimit == 0 && maxLevel == 0)
        {
            valid = false;
        }

        return valid;
    }
}
